package com.lyn.pluginbazaar.config;

import com.lyn.pluginbazaar.annotation.Login;
import com.lyn.pluginbazaar.utils.CheckUtil;
import com.lyn.pluginbazaar.utils.TokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 请求拦截器
 */
public class WebInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return check(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private boolean check(HttpServletRequest request,HttpServletResponse response,Object handler){
        if (handler instanceof HandlerMethod){
            Method method = ((HandlerMethod) handler).getMethod();
            if (method.isAnnotationPresent(Login.class)){
                return TokenUtil.checkToken(request,response);
            }
        }
        return true;
    }

}
